package com.treasure.service.third.controller;

import com.treasure.service.annotation.LogInfo;
import com.treasure.service.commons.lang.util.StringUtil;
import com.treasure.service.commons.lang.util.XMLUtil;
import com.treasure.service.constant.Constants;
import com.treasure.service.dto.AffirmPayResult;
import com.treasure.service.dto.PrepareResult;
import com.treasure.service.enums.PayEnum;
import com.treasure.service.third.service.PayService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.io.IOException;

/**
* @Description:    充值结算
* @Author:         panxinwen
* @CreateDate:     2018/10/21 12:23
* @Version:        1.0
*/
@Api(value = "充值结算",description = "对接微信及三方充值服务")
@RestController
@RequestMapping("/pay/v1")
public class PayController {

    @Autowired
    private PayService payService;

    private Logger logger = LoggerFactory.getLogger(this.getClass());

    @LogInfo(log="三方充值(划扣，微信预充值)",isPrint = true)
    @ApiOperation(value = "三方充值(划扣，微信预充值)",notes = "三方充值(划扣，微信预充值)")
    @PostMapping("/charge")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "payType", value = "充值类型(1:公众号支付 2:h5支付)",required = true,dataType = "int",paramType = "query"),
            @ApiImplicitParam(name = "bizId", value = "业务流水号",required = true,dataType = "long",paramType = "query"),
            @ApiImplicitParam(name = "amount", value = "充值金额(单位分)",required = true,dataType = "long",paramType = "query"),
            @ApiImplicitParam(name = "bizType", value = "业务类型(1:会员购买)",required = true,dataType = "int",paramType = "query"),
            @ApiImplicitParam(name = "clientIp", value = "调用支付的客户端ip",required = false,dataType = "String",paramType = "query"),
            @ApiImplicitParam(name = "userId", value = "用户id",required = true,dataType = "int",paramType = "query")
    })
    public ResponseEntity charge(
            @RequestParam(value = "payType", required = true) Integer payType,
            @RequestParam(value = "bizId", required = true) Long bizId,
            @RequestParam(value = "amount", required = true) Long amount,
            @RequestParam(value = "bizType", required = true) Integer bizType,
            @RequestParam(value = "clientIp", required = false) String clientIp,
            @RequestParam(value = "userId", required = true) Long userId
    ) throws Exception {
        //购买会员、
        PrepareResult prepareResult = payService.createPayOrder(payType,bizId,PayEnum.getByValue(bizType),amount,userId,clientIp);
        return  ResponseEntity.ok(prepareResult);

    }
    @LogInfo(log="微信支付结果通知", isPrint = true)
    @PostMapping(value = "/notify")
    public void getnotify(HttpServletRequest request, HttpServletResponse response) {
        try {

            BufferedReader reader = request.getReader();
            String line = "";
            StringBuffer inputString = new StringBuffer();
            while ((line = reader.readLine()) != null) {
                inputString.append(line);
            }
            request.getReader().close();
            AffirmPayResult affirmPayResult;
            logger.info("微信支付结果通知：{}", inputString.toString());
            affirmPayResult =XMLUtil.XMLToObj(inputString+"",AffirmPayResult::new);
            affirmPayResult.setXml(inputString.toString());
            if (StringUtil.isEqual(affirmPayResult.getReturn_code(), Constants.PayStatus.W_SUCCESS)) {
                String[] attach = affirmPayResult.getAttach().split("-");
//                affirmPayResult.setBizId(Long.parseLong(attach[1]));
//                affirmPayResult.setPayId(Long.parseLong(attach[2]));
//                affirmPayResult.setFrom(Long.parseLong(attach[3]));
//                affirmPayResult.setTo(Long.parseLong(attach[4]));
                affirmPayResult.setIs_returned(true);
                affirmPayResult.setIs_resulted(StringUtil.isEqual(affirmPayResult.getResult_code(), Constants.PayStatus.W_SUCCESS));
                affirmPayResult.setXml(inputString.toString());

            }

            payService.notify(affirmPayResult);

        } catch (Exception e) {

            logger.error("活动报名费支付回调通知异常：{}", e);

        }
        try {
            response.getWriter().write("<xml><return_code><![CDATA[SUCCESS]]></return_code></xml>");
        } catch (IOException e) {
            e.printStackTrace();
        }

    }
}
